package com.mashibing.internalcommon.util;

import com.auth0.jwt.JWT;
import com.auth0.jwt.JWTCreator;
import com.auth0.jwt.algorithms.Algorithm;
import com.auth0.jwt.interfaces.DecodedJWT;
import com.mashibing.internalcommon.constant.TokenConstants;
import com.mashibing.internalcommon.dto.TokenResult;

import java.util.Calendar;
import java.util.Date;
import java.util.HashMap;

public class JwtUtils {

    private static final String SALT = "@#$&*)$kkd";
    private static final String JWT_KEY_PHONE = "phone";

    // 乘客是1，司机是2
    private static final String JWT_KEY_IDENTITY = "identity";

    // token类型
    private static final String JWT_TOKEN_TYPE = "tokenType";

    // 用于生成每次的token值不同
    private static final String JWT_TOKEN_TIME = "tokenTime";


    // 生成token
    public static String generatorToken(String passengerPhone, String identity,String tokenType) {
        HashMap<String, String> map = new HashMap<>();
        map.put(JWT_KEY_PHONE, passengerPhone);
        map.put(JWT_KEY_IDENTITY, identity);
        map.put(JWT_TOKEN_TYPE, tokenType);
        map.put(JWT_TOKEN_TIME, Calendar.getInstance().getTime().toString());

        JWTCreator.Builder builder = JWT.create();
        map.forEach(builder::withClaim);

        return builder.sign(Algorithm.HMAC256(SALT));

    }

    // 解析token
    public static TokenResult parseToken(String token) {
        DecodedJWT verify = JWT.require(Algorithm.HMAC256(SALT)).build().verify(token);
        String phone = verify.getClaim(JWT_KEY_PHONE).asString();
        String identity = verify.getClaim(JWT_KEY_IDENTITY).asString();

        TokenResult tokenResult = new TokenResult();
        tokenResult.setPhone(phone);
        tokenResult.setIdentity(identity);
        return tokenResult;
    }

    public static TokenResult checkToken(String token) {
        TokenResult jwtToken = null;
        try {
            jwtToken = JwtUtils.parseToken(token);
        } catch (Exception e) {
            // TODO
        }
        return jwtToken;
    }

    public static void main(String[] args) {
        String token = generatorToken("18434371986", "1", TokenConstants.ACCESS_TOKEN_TYPE);
        System.out.println(token);
    }

}
